from django.shortcuts import render

from django.http.response import JsonResponse, HttpResponse
from django.core import serializers

import json
from .models import *

# 筛选出在task_line中的MemberPeople
def search_operator(task_line):
    select_operators = []
    for operator in MemberPeople.objects.all():
        if operator.name_data in task_line:
            select_operators.append(operator.to_dict())
    select_operators_dict = {item["name"]: item for item in select_operators}
    return select_operators_dict

# 从taskData中筛选出含有nameData的部分
def parse_task(nameData,taskData):
    result_data = []
    for task_line in taskData.split():
        if nameData in task_line:
            task_line_split = task_line.split("-")
            task_line_part01 = "-".join(task_line_split[:-1])
            task_line_part02 = task_line_split[-1]

            # 遍历MemberPeople寻找task_line包含的实施
            select_operators_dict_01 = search_operator(task_line_part01)
            select_operators_dict_02 = search_operator(task_line_part02)

            # 为实施设置高亮颜色
            for info in select_operators_dict_02.values():
                info.update({"color": "#626aef"})
            
            for info in select_operators_dict_01.values():
                info.update({"color": ""})
            
            select_operators = list(select_operators_dict_02.values())
            for k,v in select_operators_dict_01.items():
                if k in select_operators_dict_02:
                    continue
                select_operators.append(v)

            result_data.append({
                "details": f"{task_line_part01}-<span class='highlight'>{task_line_part02}</span>",
                "operators": select_operators,
            })
    return result_data




# Create your views here.

def test_search_task(request):
    for i in MemberPeople.objects.all():
        print(i.name_data,i.phone_number)



def post_search_task(request):
    if request.method == "POST":
        # {'nameData': 'abc', 'dateData': '2025-08-04'}
        data = json.loads(request.body)
        # print(data)
        nameData = data["nameData"]
        dateData = data["dateData"]

        # nameData为空则返回
        if not len(nameData):
            return JsonResponse({'msg': f"查询数据为空，请正确输入数据"}, status=400)
        
        try:
            select_object = DailyTask.objects.get(create_date=dateData)
            taskData = select_object.text_data
            # print(select_object.text_data)
            # print(taskData.text_data)
        except DailyTask.DoesNotExist as e:
            json_response =  JsonResponse({'msg': f"{dateData}的数据暂未录入"}, status=400)
        
        else:
            result_data =  parse_task(nameData,taskData)
            json_response =  JsonResponse({'msg': 'OK',"data":result_data})
    else:
        json_response =  JsonResponse({'msg': '仅支持POST请求'}, status=400)
    return json_response